package br.com.amadeus.android.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.client.ClientProtocolException;

import android.os.Environment;

public class ImageUtil {
	
	public static String saveImageUser(String url) throws ClientProtocolException, IOException{
    	RESTFileContent rfc = new RESTFileContent();
    	InputStream is = rfc.getRESTFileContent(url);
    	
    	byte data[] = new byte[512];
		int count = 0;
		int total = 0;
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		while ((count = is.read(data)) > 0) {
			total += count;
			// publishing the progress....
			baos.write(data, 0, count);
		}
		
		File root = Environment.getExternalStorageDirectory();
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        String rootArchive = extStorageDirectory + ConstantsAmadeusDroid.ROOT_ARCHIVES;
        if (root.canWrite()){
        	File myFile = new File(rootArchive, "image_user.png");
        	FileOutputStream fOut = new FileOutputStream(myFile);
        			            	
        	fOut.write(baos.toByteArray());
        	fOut.close();
        }
        
        String s = new String(baos.toByteArray());
        
        baos.close();
        is.close();
        
        return s;
    }
    
    public static void saveImageUser(String url, String imageName) throws ClientProtocolException, IOException{
		RESTFileContent rfc = new RESTFileContent();
    	InputStream is = rfc.getRESTFileContent(url);
    	
    	byte data[] = new byte[512];
		int count = 0;
		int total = 0;
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		while ((count = is.read(data)) > 0) {
			total += count;
			// publishing the progress....
			baos.write(data, 0, count);
		}
		
		File root = Environment.getExternalStorageDirectory();
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        String rootArchive = extStorageDirectory + ConstantsAmadeusDroid.ROOT_ARCHIVES;
        if (root.canWrite()){
        	File myFile = new File(rootArchive, imageName + ".png");
        	FileOutputStream fOut = new FileOutputStream(myFile);
        			            	
        	fOut.write(baos.toByteArray());
        	fOut.close();
        }
        
        baos.close();
        is.close();
	}

}
